<template>
  <div class="create-task">
    <div class="content-wrap">
      <div class="target">
        <div class="title c38">
          <span class="bggreen"></span>
          拜访对象
          <p @click="toSelectpeople()" class="c78" style="margin-left: 300rpx;font-size: 28rpx;">从通讯录选择</p>
        </div>
        <ul>
          <li>
            <div class="target-left c78">
              姓名/单位
            </div>
            <div class="target-right">
              <input class="c39" type="text"  @blur="toname" :placeholder="name || '请输入客户名称'">
            </div>
          </li>
          <li>
            <div class="target-left c78">
              联系方式
            </div>
            <div class="target-right">
              <input class="c39" type="number"  @blur="tophone" :placeholder="phone || '请输入客户电话'">
            </div>
          </li>

          <li>
            <div class="target-left c78">
              所属公司
            </div>
            <div class="target-right">
              <input class="c39" type="number"  @blur="tointervieweeCompany" :placeholder="intervieweeCompany || '请输入所属公司'">
            </div>
          </li>
          <li>
            <div class="target-left c78">
              公司职位
            </div>
            <div class="target-right">
              <input class="c39" type="number"  @blur="tointervieweePosition" :placeholder="intervieweePosition || '请输入公司职位'">
            </div>
          </li>
        </ul>
      </div>
      <div class="target">
        <div class="title c38">
          <span class="bgblue"></span>
          拜访地点
        </div>
        <ul>
          <li @click="page_tap('chooseAddr')">
            <div class="target-left c78">
              地理位置
            </div>
            <div class="target-right" style="margin-top: -17rpx;">
              <input type="text" value="visitingAddr" class="pt15 w100p phe8 flex1 over_1" readonly disabled placeholder="请选择位置"
                     v-model="visitingAddr" style="width: 400rpx;margin-top: -5rpx;text-align: right;margin-right: 5rpx;">
            </div>
          </li>
        </ul>
      </div>
      <div class="time">
        <div class="title c38">
          <span class="bgyellow"></span>
          拜访日期
        </div>
        <div class="content-bottom">
          <div class="content-bottom-left c78">
            时间
          </div>
          <div class="content-bottom-right c38">
            <datatimea :placeholder="visitingTime || '请选择日期'" @change="startEvent" :start="begin"></datatimea>
            <image class="w16 h16 mt2 ml7" :src="downImg"></image>
          </div>
        </div>
      </div>
      <div class="task-content" style="margin-top: 20rpx;">
        <div class="title c38">
          <span class="bgeee"></span>
          拜访目的
        </div>
        <div class="content ">
           <textarea :placeholder="visitingPurpose || '请输入拜访目的'" @blur="toVisitingPurpose" style="width: 100%;"/>
        </div>
      </div>
      <div class="task-content" style="margin-top: 20rpx;">
        <div class="title c38">
          <span class="bg55"></span>
          拜访结果
        </div>
        <div class="content">
           <textarea :placeholder="visitingResult || '请输入拜访结果'" @blur="toVisitingResult" style="width: 100%;"/>
        </div>
      </div>
      <div class="task-content" style="margin-top: 20rpx;">
        <div class="title c38">
          <span class="bg38"></span>
          拜访内容
        </div>
        <div class="content">
           <textarea :placeholder="visitingContent || '请输入拜访内容'" @blur="toVisitingContent" style="width: 100%;"/>
        </div>
      </div>

      <div class="task-content" style="margin-top: 20rpx;">
        <div class="title c38">
          <span class="bga8"></span>
          跟进计划
        </div>
        <div class="content ">
           <textarea :placeholder="visitingPlan || '请输入跟进计划'" @blur="toVisitingPlan" style="width: 100%;"/>
        </div>
      </div>
      <div class="target">
        <div class="title c38">
          <span class="bgblue"></span>
          上传图片
        </div>
        <div class="content ">
          <div class="disflex wrap">
            <div class="bgfff bdash_a8 w100 h100 mr7 mb7 posre"
                 v-for="(v,k) in visitingLbsUrl"
                 :key="k">
              <img :src="v"
                   alt=""
                   class="w100p h100p"
                   mode="aspectFill">
              <img src="https://myy-one-stand.oss-cn-beijing.aliyuncs.com/yimai_photos/user/del.png"
                   alt=""
                   class="w20 h20 posab right2 top2"
                   @click="delImg(k)">
            </div>
            <div
                 class="bgfff bdash_a8 w100 h100 add_img mr7 mb7"
                 @click="uploadpic('self', 9)">
            </div>
        </div>
      </div>
    </div>
      <div class="confirm-btn" @click="preservation">
        保存
      </div>
    </div>
  </div>
</template>

<script>
  import WXAJAX from '../../../utils/request.js';
  import datatimea from '../../../components/biaofun-datetime-picker/biaofun-datetime-picker.vue';
  import {mapStates,mapMutations} from 'vuex'
  import util from '../../../utils/index'
  import amapFile from '@/libs/amap-wx.js'
  export default {
    data(){
      return{
        downImg:WXAJAX.imgBackUrl + '/product-index/icon_right-s.png',
        //type 用来分辩到底是创建还是修改任务
        type:'',

        visitingId:0,
        visitingType:1,
        visitingTime:'',
        visitingPurpose:'',
        visitingContent:'',
        visitingResult:'',
        visitingLbsUrl:'',
        visitingAddr:'',
        visitingAddrInfo:'',
        visitingPlan:'',
        name:'',
        phone:'',
        customerInfo:'',

        intervieweeCompany:'',//公司
        intervieweePosition:'',//职位

        staffid:'',
        selectInfo:'',
        begin:'2020-5-21 14:39',
        userId:wx.getStorageSync('userId'),
        address:'',
        visitingLbsUrl: [],//个人图片
        customerInfo:[],
      }
    },
    onLoad() {
      this.companyId = wx.getStorageSync('COMPANYID')
      this.type = 1
      this.taskCustomerId = wx.getStorageSync('COMPANYID')
    },
    watch:{
      //判断是否为编辑任务，1为创建，2为编辑
      type(newVal,oldVal){
        if(newVal == 1){

        }else{
          this.isLoading = true;
          this.getQueryMyTaskDetail()
        }
      },
    },
    onShow() {
      if(wx.getStorageSync('VisitAddr')){
        this.visitingAddr=wx.getStorageSync('VisitAddr');
        this.visitingAddrInfo=wx.getStorageSync('district');

        wx.setStorageSync('VisitAddr','');
        wx.setStorageSync('full_address','');
        wx.setStorageSync('district','');
      }


      this.staffid = this.$store.state.staffId
      // this.customerInfo = this.$store.state.customerInfo
      if(wx.getStorageSync('customerList')){
        this.customerInfo = wx.getStorageSync('customerList');
        this.name = this.customerInfo[1]
        this.phone = this.customerInfo[2]
        this.intervieweeCompany = this.customerInfo[3]
        wx.setStorageSync('customerList','');
      }


      // if(this.$store.state.customerInfo){
      //   this.addcustomer()
      // }
    },
    mounted(){
    },
    methods:{


      getStartDate() {
         var thisDay= new Date();
           var year = thisDay.getFullYear();
           var month = thisDay.getMonth() + 1;
           var day = thisDay.getDate();
           var hh = thisDay.getHours();
           var mm = thisDay.getMinutes();
           var timer = year + "-";
           timer += month + "-";
           timer += day + ' '
           if(hh < 10)
           timer += "0";
           timer += hh + ":";
            if (mm < 10)
            timer += '0';
            timer += mm
           return timer
      },
      timestampToTime(timestamp){
            var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
           var Y = date.getFullYear() + '-';
           var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
           var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
           var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
           var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes());
            return Y+M+D+h+m;
          },


      toSelectpeople(){
        var id = this.$store.state.companyId
        wx.navigateTo({
          url:`../selectpeople/main?id=${id}`
        })
      },
      resetAddr() {//获取经纬度
          wx.showLoading({
              title: '定位中...',
              mask: true
          });
          var v = this;
          uni.getLocation({
              type: 'wgs84',
              success: function (res) {
                  let latitude = res.latitude;
                  let longitude = res.longitude;
                  wx.chooseLocation({
                      latitude,
                      longitude,
                      success: function (res) {
                          v.visitingAddr = res.address
                      }
                  })
                  wx.hideLoading();
              },
              fail: function (err) {
                  v.isShowAuthorize=true;
                  wx.hideLoading();

              },
              complete: function () {
                  wx.hideLoading();
              }
          })
      },
      toVisitingPurpose(e){
        this.visitingPurpose = e.detail.value
      },
      toname(e){
        this.name = e.detail.value
      },
      tointervieweeCompany(e){
        this.intervieweeCompany = e.detail.value
      },
      tointervieweePosition(e){
        this.intervieweePosition = e.detail.value
      },
      tophone(e){
        this.phone = e.detail.value
      },
      toVisitingAddrInfo(e){
        this.visitingAddrInfo = e.detail.value
      },
      async uploadpic (str, count) {
        let a = this.card_msg;
        if (str == 'self' && this.visitingLbsUrl.length >= 9) {
          wx.showToast({
            title: '最多选择九张！',
            duration: 1500,
            icon: 'none'
          });
          return
        }
        let path = await util.chooseImage('file', count);

        if (Object.prototype.toString.call(path) !== '[object Array]') return;
        this.uploadImgFun(path, 0, str)
      },
      // 递归上传
      async uploadImgFun (arr, index = 0, str) {
        await this.uploadImg(arr[index], str)
        if (index < arr.length - 1) {
          this.uploadImgFun(arr, index + 1, str)
        }
      },
      uploadImg (path, str) {
        let v = this;
        wx.showLoading({ mask: true });
        return WXAJAX.UploadImage(path).then((data) => {
          wx.hideLoading();
          data = JSON.parse(data);
          if (data.code == '200') {
            if (str == 'user') {
              v.$set(v.card_msg, 'picchecked', WXAJAX.imgBackUrl + data.data);
            } else if (str == 'self') {
              v.visitingLbsUrl.push(WXAJAX.imgBackUrl + data.data);
            }
          } else {
            wx.showToast({
              title: '网络异常',
              duration: 2000,
              icon: 'none'
            })
          }
        }).catch((err) => {
          wx.hideLoading();
          console.log('err -- ', err);
        })

      },
      delImg (index) {//删除图片
        wx.showLoading();
        this.visitingLbsUrl.splice(index, 1);
        wx.hideLoading();
      },
      page_tap(url) {
        wx.navigateTo({url: '../../' + url + '/main?type=1' })
        //type=1分辨地理位置不需要更新接口
      },
      toVisitingContent(e){
        this.visitingContent = e.detail.value
      },
      toVisitingResult(e){
        this.visitingResult = e.detail.value
      },
      toVisitingPlan(e){
        this.visitingPlan = e.detail.value
      },
     startEvent(data){
        console.log(data)
        this.visitingTime = data.fmt1
      },
      addcustomer(){ //添加拜访客户
        this.isLoading = true;
        let that=this
        let intervieweeCardId=0;
        if(this.staffid){
          intervieweeCardId=this.staffid[0];
        }else{
          intervieweeCardId=0;
        }
        let params={
              intervieweeCardId:intervieweeCardId,
              intervieweeName:this.name,
              intervieweePhone:this.phone,
            }
        console.log('params',params)
        WXAJAX.POST(
            params,
            "",
            "/visiting/add",'','',1
          ).then((data) => {
            that.visitingId=data.visitingId;
            that.getAddTaskCustomer();
          });

          this.isLoading = false;
          wx.hideLoading();
      },
      preservation(){
        if(this.name == '' ||this.phone == '' ||this.visitingTime == '' || this.visitingPurpose == '' || this.visitingContent == ''|| this.visitingResult == ''|| this.visitingLbsUrl == ''|| this.visitingAddr == ''|| this.visitingAddrInfo == ''){
          wx.showToast({
            title:'请将信息选填完整',
            icon:'none',
            duration:2000
          })
          return false
        }
        this.addcustomer();

      },
      async getAddTaskCustomer(){

        wx.showLoading({
          mask:true
        })
        this.isLoading = true;
        let params={
              visitingId:this.visitingId,
              visitingType:1,
              visitingTime:this.visitingTime,
              visitingPurpose:this.visitingPurpose,
              visitingContent:this.visitingContent,
              visitingResult:this.visitingResult,
              visitingLbsUrl:this.visitingLbsUrl.toString(),
              visitingAddr:this.visitingAddr,
              visitingAddrInfo:this.visitingAddrInfo,
              visitingPlan:this.visitingPlan,
              intervieweeCompany:this.intervieweeCompany,
            }
            console.log(params);
        try {
          let data = await WXAJAX.POST(
            params,
            "",
            "/visitingInfo/add",'','',1
          );

          wx.showToast({
            title:'已成功！',
            duration:2000
          })
          this.isLoading = false;
          setTimeout(function(){
            wx.navigateBack({
              delta:1
            })
          },1000)
        } catch (error) {
          this.isLoading = false;
          wx.hideLoading();
          // console.log(".............", error);
        }
      }
    },
    destroyed(){
      this.$store.state.staffId = []
      this.$store.state.selectRecordsInfo = []

    },
    components:{
      datatimea
    }

  }
</script>

<style scoped>
  textarea{
    height: 160rpx;
  }
 .create-task{
   height: 100%;
   box-sizing: border-box;
   display: flex;
   flex-direction: column;
 }
 .content-wrap{
   padding:20upx 30upx 0 20upx;
   flex: 1;
   overflow: auto;
 }
 .task-content{
   background: #FFFFFF;
   border-radius: 20upx;
 }
 .title{
   font-size: 32upx;
   color: #383838;
   display: flex;
   align-items: center;
   padding:0upx 30upx 0 30upx;
   height: 88upx;
   font-weight:bold;
   border-bottom: 1upx solid #F8F8F8;
 }
 .title span{
   width: 20upx;
   height: 20upx;
   margin-right: 17upx;
   border-radius: 50%;
 }
 .content{
   padding:30upx 30upx 0 30upx;
   min-height: 140upx;
   font-size: 30rpx;
   /* height: 72upx; */
   line-height: 30rpx;
   overflow: hidden;
   border-bottom:1upx solid #F8F8F8;
 }
 .content-bottom{
   height: 88upx;
   display: flex;
   padding:0upx 30upx 0 30upx;
   justify-content: space-between;
   align-items: center;
   font-size: 28upx;
 }
 .content-bottom-right{
   display: flex;
 }
 .target{
   background: #FFFFFF;
   border-radius: 20upx;
   margin-top: 20upx;
 }
 .target ul{
   padding:0  30upx;
   display: flex;
   flex-direction: column;
 }
 .target ul li{
   height: 88upx;
   font-size: 28upx;
   display: flex;
   justify-content: space-between;
   align-items: center;
 }
 .target ul li input{
   height: 100%;
   width: 200upx;
   margin-right: 5upx;
 }
 .target-right{
   display: flex;
 }
 .time{
   background: #FFFFFF;
   border-radius: 20upx;
   margin-top: 20upx;
 }
 .choice-article{
   width: 240upx;
   overflow: hidden;
   text-overflow:ellipsis;
   white-space:nowrap;
   text-align:right
 }
 .confirm-btn{
   height: 98upx;
   line-height: 98upx;
   text-align: center;
   color: #FFFFFF;
   font-size: 36upx;
   background:linear-gradient(90deg,rgba(118,218,217,1),rgba(81,205,204,1));
 }
 .numinput{
   padding-right: 32upx;
   text-align: right;
 }
</style>
